package cn.edu.cqu.services.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.cqu.domains.Contact;
import cn.edu.cqu.services.ContactCRUD;

@Service("ContactCRUDHibernate")
public class ContactCRUDHibernate implements ContactCRUD {

	private HibernateTemplate ht;
	private Session session;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		ht = new HibernateTemplate(sessionFactory);
		session = ht.getSessionFactory().openSession();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Contact> getAll(int pageNo,int pageSize) {
		String hql = "from Contact";
		Query query = session.createQuery(hql);
		return query.setFirstResult((pageNo-1)*pageSize).setMaxResults(pageSize).list();
	}
	
	@Override
	public Contact getByID(String cID) {
		return ht.get(Contact.class, cID);
	}

	@Override
	@Transactional
	public Contact edit(Contact contact) {
		return ht.merge(contact);
	}

	@Override
	@Transactional
	public void deleteByID(String cID) {
		Contact contact = this.getByID(cID);
		ht.delete(contact);
	}

}
